package com.platform.framework.threads;


import org.apache.log4j.Logger;

import com.platform.framework.entity.pub.TradeFlow;
import com.platform.framework.gateway.alipay.config.AlipayConfig;
import com.platform.framework.gateway.alipay.inf.AlipayGateway;
import com.platform.framework.serviceinf.pub.TradeFlowService;
import com.platform.framework.util.net.tool.HttpUtil;
import com.platform.framework.util.pub.ContextUtil;
import com.platform.framework.util.pub.Validation;
import com.platform.framework.util.sign.SignUtil;
import com.platform.framework.vo.states.PayGate;
import com.platform.framework.vo.states.PayResult;
import com.platform.framework.vo.transfer.TransportLayer;

/**
 * 支付宝扫码支付轮询支付结果线程类
 * @author ly-liugaoyang
 * @create_date 2016年10月20日
 */
public class QueryPayResultThread extends Thread{
	
	private static Logger logger = Logger.getLogger(QueryPayResultThread.class);
	
	private AlipayGateway alipayGateway = (AlipayGateway)ContextUtil.getContext().getBean("alipayGateway");
	
	private TransportLayer transportLayer ;
	
	private TradeFlowService tradeFlowService;
	
	private Boolean continueQuery = true; // 是否继续查询

	public QueryPayResultThread( TransportLayer transportLayer,
			TradeFlowService tradeFlowService) {
		super();
		this.transportLayer = transportLayer;
		this.tradeFlowService = tradeFlowService;
	}

	@Override
	public void run() {
		int queryCount = 1;
		transportLayer.setPayGate(PayGate.QUERY_TRADE_RESULT);
		while (continueQuery) {
			logger.info("-----------------进入第" + queryCount + "次轮询…… ^_^");
			try {
				if (queryCount == AlipayConfig.queryCount) {
					transportLayer.setPayGate(PayGate.CANCEL_TRADE);
					TradeFlow tradeFlow = tradeFlowService.getTradeFlowByOrderId(transportLayer.getOrderNo()).get(0);
					tradeFlow.setPayResult(PayResult.QR_PAY_TIMEOUT); // 支付超时 手动撤单
					String cancelResult = alipayGateway.cancelTrade(transportLayer);
					if (cancelResult.equals("success")) { // 撤单成功
						tradeFlowService.saveOrUpdate(tradeFlow); // 更改订单状态
						logger.info("[tradelog"+transportLayer.getOrderNo()+"]支付宝扫码支付状态已经更改，支付结果为："+PayResult.QR_PAY_TIMEOUT+"，订单号"+ tradeFlow.getOrderNo() + "入库。");
						sendMsgToUser(tradeFlow);
					}
					break;
				}
				
				Thread.sleep(AlipayConfig.timeout); // 默认每隔5s查一次
				String queryResult = alipayGateway.queryTradeResult(transportLayer);
				if (!Validation.isEmpty(queryResult)&& queryResult.equals(PayResult.TRADE_SUCCESS)) {
					TradeFlow tradeFlow = tradeFlowService.getTradeFlowByOrderId(transportLayer.getOrderNo()).get(0);
					tradeFlow.setPayResult(queryResult.equals(PayResult.TRADE_SUCCESS)?queryResult:PayResult.TRADE_FAIL);
					tradeFlow.setBuyerUserId(transportLayer.getBuyerUserId());
					tradeFlowService.saveOrUpdate(tradeFlow); // 更改订单状态
					logger.info("[tradelog"+transportLayer.getOrderNo()+"]支付宝扫码支付状态已经更改，支付结果为："+queryResult+"，订单号"+ tradeFlow.getOrderNo() + "入库。");
					// 应该通知商务后台，做好信息同步。
					sendMsgToUser(tradeFlow);
					continueQuery = false;
				}
			} catch (Exception e) {
				logger.error("[tradelog"+transportLayer.getOrderNo()+"]Thread Exception : " + e);
				e.printStackTrace();
				break;
			}
			
			queryCount = queryCount + 1; // 默认查询十次
		}
		
		
	}
	
	/**
	 * 将支付结果通知商户
	 * @param tradeFlow
	 */
	private void sendMsgToUser (TradeFlow tradeFlow) {
		String requestUrl = "";
		if (!Validation.isEmpty(tradeFlow.getNotifyUrl())) {
			if (tradeFlow.getNotifyUrl().contains("?")) {
				requestUrl = tradeFlow.getNotifyUrl() + "&orderNo=" + tradeFlow.getOrderNo() + "&payResult=" + tradeFlow.getPayResult() + "&sign=" + SignUtil.MD5Sign(tradeFlow)  ;
			} else {
				requestUrl = tradeFlow.getNotifyUrl() + "?orderNo=" + tradeFlow.getOrderNo() + "&payResult=" + tradeFlow.getPayResult() + "&sign=" + SignUtil.MD5Sign(tradeFlow)  ;
			}
			logger.info("[tradelog"+transportLayer.getOrderNo()+"] user requestUrl : "+ requestUrl);
			String httpResult = HttpUtil.executeHttpGet(requestUrl);
			logger.info("[tradelog"+transportLayer.getOrderNo()+"]send Msg to user success , result is " + httpResult);
		}
		logger.info("[tradelog"+transportLayer.getOrderNo()+"]支付宝扫码支付完成调用，信息已经成功回调至：" + tradeFlow.getNotifyUrl());
	}
}
